<template>
  <div class="main-container">
    <TableHeadSearch @searchForm="searchForm" />
    <TableHeader :can-collapsed="false">
          <template v-slot:left>
            <el-button
              type="primary"
              size="small"
              icon="PlusIcon"
              @click="onAddItem"
              >添加
            </el-button>
          </template>
    </TableHeader>
    
    <TableBody
      ref="tableBody"
      :tableLoading="tableLoading"
      :tableConfig="tableConfig"
      :tableColumns="tableColumns"
      :tableOperations="tableOperations"
      :tableData="dataList"
    >
   
      <template #tableConfig>
        <template>
            <el-button
              type="primary"
              size="small"
              icon="PlusIcon"
              @click="onAddItem"
              >添加
            </el-button>
          </template>
  
        <div
          class="flex justify-between padding"
          style="border-bottom: 1px dashed var(--el-border-color-light)"
        >
          <el-link :underline="false">表格设置</el-link>
          <div>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.border">表格边框</el-checkbox>
            </span>
            <span class="margin-right">
              <el-checkbox v-model="tableConfig.stripe">斑马纹</el-checkbox>
            </span>
            <!-- <span class="margin-right">
              <el-checkbox v-model="tableConfig.multiSelect">多选</el-checkbox>
            </span> -->

            <SortableTable
              class="margin-left"
              :table-props="tableColumns"
              @update="onUpdateTable"
            />
          </div>
        </div>
   
      </template>
    </TableBody>
    <!-- <TableFooter
      ref="tableFooter"
      @refresh="doRefresh"
      @pageChanged="doRefresh"
    /> -->
   
  <Dialog ref="dialog"  title="编辑部门信息" :form-items="formItems">
      <template #content>
        <BaseForm
         class="padding-left padding-right"
          ref="baseForm"
          :form-items="formItems"
        >
            <template #prefix>
            <el-form-item :label="departmentFormItem.label">
              <TreeSelector
                v-model:value="departmentFormItem.value"
                placeholder="请选择上级部门"
                :data="dataList"
                :dataFields="{
                  label: 'departmentName',
                  value: 'departmentOid',
                }"
              />
            </el-form-item>
          </template>
        </BaseForm>
      </template>
  </Dialog>

  </div>

</template>


<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import {computed, onMounted, reactive, ref } from "vue";
import {
  showSuccessMessage,
} from "@/components/types";
import { useDataTable, usePost } from "@/hooks";
import { queryDepartmentList, saveDepartment,updateDepartment, deleteDepartment } from "@/api/url";
import type { TableFooter,BaseFormType, DialogType } from "@/components/types";
import {
  Delete,
  CirclePlus,
  Refresh as RefreshIcon,
} from "@element-plus/icons";
import { depArraytotree} from "@/utils/index";
const {
  handleSuccess,
  selectRows,
  dataList,
  tableConfig,
  tableLoading,
  handleSelectionChange,
} = useDataTable();
const post = usePost();
const tableColumns = reactive([
  {
    label: "部门名称",
    prop: "departmentName",
  },
  {
    label: "部门编号",
    prop: "departmentCode",
  },
  {
    label: "备注",
    prop: "remark",
  },
  {
    label: "上级部门",
    prop: "parentName",
  },
  
]);
const tableOperations = reactive([
  {
    text: "编辑",
    key: "edit",
    type: "primary",
    size: "mini",
    handler: (row: any) => handleEdit(row),
  },
   {
    text: "删除",
    key: "delete",
    type: "danger",
    size: "mini",
    handler: (row: any) => onDeleteItem(row),
  },
]);
const tableFooter = ref<TableFooter>();
const dialog = ref<DialogType>();
const baseForm = ref<BaseFormType>();
const departmentFormItem = reactive({
  label: "上级部门",
  name: "parentOid",
  value: 0,
  hidden: true,
  placeholder: "请选择上级部门",
  selectOptions: {},
  reset() {
    this.value = 0;
  },
});

const formItems = reactive([
     {
        label: '',
        type: 'input',
        hidden: true,
        name: 'departmentOid',
        value: "",
        reset() {
          this.value = "";
        },
     },
     {
        label: '',
        type: 'input',
        hidden: true,
        name: 'versionNo',
        value: 0,
        reset() {
          this.value = 0;
        },
     },
     departmentFormItem,
     {
        label: '部门名称',
        type: 'input',
        name: 'departmentName',
        value: ref(""),
        maxLength: 20,
        placeholder: "请输入部门名称",
        validator: (item: any) => {
          if (!item.value) {
            ElMessage.error(item.placeholder);
            return false;
          }
            return true;
        },
        reset() {
          this.value = ref("");
        },
      },
      {
        label: '部门编号',
        type: 'input',
        name: 'departmentCode',
        value: ref(""),
        maxLength: 20,
        placeholder: "请输入部门编号",
        validator: (item: any) => {
          if (!item.value) {
            ElMessage.error(item.placeholder);
            return false;
          }
            return true;
        },
        reset() {
          this.value = ref("");
        },
      },
      {
        type: 'textarea',
        label: '备注',
        name: 'remark',
        value: ref(""),
        maxLength: 20,
        reset() {
          this.value = ref("");
        },
      },
      

  ]);
function handleEdit(data: any) {
  onUpdateItem(data);
}
const onUpdateItem = (item: any) => {
  formItems.forEach((it) => {
    const propValue = item[it.name];
    it.value = propValue;
  });
  departmentFormItem.value = item.parentId;

  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      let params : any = baseForm.value?.generatorParams();
      submitForm(updateDepartment,params)
      dialog.value?.close();
    }, 1000);
  });
};

function doRefresh() {
  tableFooter.value?.setPageSize(100);
  post({
    url: queryDepartmentList,
    data: {
      // page: tableFooter.value?.withPageInfoData(),
       page: {
          currentPage:1,
          perPage:200,
       },
    },
  })
    .then((res: any) => {
      let allDepartments = depArraytotree(res.data);
      const obj = {
        data: allDepartments
      };
      handleSuccess(obj);
      // tableFooter.value?.setTotalSize(res.pageUI.total);
      tableConfig["tree"] = {rowKey:"departmentOid",child:allDepartments}
    })
    .catch(console.log);
}

function submitForm(submitUrl: string ,params: any) {
   post({
    url: submitUrl,
    data: params,    
  })
  .then((res: any) => {
     ElMessage.success("数据提交成功！");
     doRefresh();
  })
  .catch(console.log);
}

const onAddItem = () => {
  baseForm.value?.resetParams();
  dialog.value?.show(() => {
    if (!baseForm.value?.checkParams()) {
      return;
    }
    (dialog.value as any).loading = true;
    setTimeout(() => {
      submitForm(saveDepartment,baseForm.value?.generatorParams())
      dialog.value?.close();
    }, 1000);
   
  });
};

function onDeleteItem(data: any) {
   post({
      url: deleteDepartment,
      data: {
        departmentOid: data.departmentOid,
    },
  })
  .then(() => {
    doRefresh();
    showSuccessMessage("删除成功");
  })
  .catch(console.log);
 
}


function searchForm(data: any) {
  post({
    url: queryDepartmentList,
    data: {
      page: tableFooter.value?.withPageInfoData(),
      searchConditionVOList: data,
    },
  })
    .then((res: any) => {
      const obj = {
        data: res.data,
      };
      handleSuccess(obj);
      tableFooter.value?.setTotalSize(res.pageUI.total);
    })
    .catch(console.log);
}


  
function onUpdateTable(temp: Array<TablePropsType>) {
  tableColumns.length = 0;
  tableColumns.push(...temp.filter((it: TablePropsType) => it.checked));
}
function initDepartment(departmentResultList: any){
  let selectOptions : any;
  alert("departmentResultList:"+JSON.stringify(departmentResultList))
  departmentResultList.forEach((item: any) => {
     selectOptions = {
        "label" : item.departmentName,
        "value" : item.departmentOid
     }
  })
  selectOptions = Object.assign(selectOptions);   
  departmentFormItem.selectOptions = selectOptions; 
}

departmentFormItem.selectOptions = computed(() => {
   alert("dataList:"+JSON.stringify(dataList))
  return dataList.value?.map((it: any) => {
    return {
      label: it.departmentName,
      value: it.departmentOid,
    };
  });
});

onMounted(doRefresh);
</script>

<style lang="scss" scoped>

</style>
